<template>
  <div style="width: 100%; height: 100%;">
    <div id="map" style="width: 100%; height: 95%;"></div>
    <div style="position:absolute;right: 10px;width: 300px;height: 40px;top: 10px;padding:10px;z-index: 999;background-color: white;">
      <!-- 搜索面板 -->
      搜索内容：<input id="keyWord" placeholder="请输入搜索地点" @keyup="handleInput"/>
      <br/>
      <!-- 建议词面板 -->
      <div id="suggestsDiv" class="suggests"  v-if="isShowSearch && searchResultList.length > 0" >
<!--        <div style='margin-left:8px;'>建议词提示</div>-->
        <el-row v-for="result in searchResultList">
          <el-col :span="24" >
            <el-button type="text" @click="handleClickAddress(result)">{{result.name + ' ' + result.address}}</el-button>
          </el-col>
        </el-row>
      </div>
    </div>
    <div style="margin-top: 10px;" v-if="isShowEdit">
      <el-button class="btn" @click="startPoly()" style="margin-bottom: 5px">开始编辑</el-button>
      <el-button class="btn" @click="endPoly()" style="margin-bottom: 5px">结束编辑</el-button>
      <el-button class="btn" @click="clearPoly()">清空</el-button>
    </div>
  </div>

</template>

<script>
import {transformGCJ02, transformGCJ2WGS} from "@/utils/GisUtil";

export default {
  name: 'Map',
  mounted() {
    let that = this;
    setTimeout(function (){
      that.initMap();
    }, 800);
  },
  //119.513841, 35.43233
  props: {
    defaultLng: {
      type: Number,
      default: 119.513841,
    },
    defaultLat: {
      type: Number,
      default: 35.43233,
    },
    shapeType: {
      type: String,
      default: "point",
    },
    radiusCircle: {
      type: Number,
      default: 0.00,
    },
    labelTitle:{
      type: String,
      default: "",
    },
    pointList:{
      type: Array,
      default:()=>[],
    },
    fillColor:{
      type: String,
      default: "#FFFFFF",
    },
    zoom: {
      type: Number,
      default: 12,
    },
    isShowEdit: {
      type: Boolean,
      default: false,
    },
    isShowSearch: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      map: null,
      handler: null,
      polygon: null,
      polyline: null,
      polygonTool: null,
      localSearch: null,
      geocoder: null,
      markerPoint:null,
      markerTitle:null,
      searchValue: '',
      searchResultList: [],
      markerList:[],
      searchMarker:[],
      pickPointList:[],
    }
  },
  methods: {
    initMap() {
      console.log('window.T',window.T)
      if (window.T) {
        this.map = new T.Map('map');

        if(isNaN(this.defaultLng)){
          this.defaultLng = 119.513841;
          this.defaultLat =  35.43233;
        }

        console.log('中心坐标', this.defaultLng, this.defaultLat)
        //level  传参中心点经纬度，以及放大程度，最小1，最大18
        let lng_lat = transformGCJ2WGS(this.defaultLng, this.defaultLat);
        this.map.centerAndZoom(new T.LngLat(lng_lat.lng, lng_lat.lat), this.zoom); // 设置地图中心点和缩放级别
        this.map.addControl(new T.Control.Zoom()); // 添加缩放控件
        //允许鼠标双击放大地图
        // this.map.enableScrollWheelZoom();

        //根据名称进行地址解析 创建对象
        this.geocoder = new T.Geocoder();


        // 工具
        // var configPolygonTool = {
        //   showLabel: true,
        //   color: "blue", weight: 3, opacity: 0.5, fillColor: this.fillColor, fillOpacity: 0.5
        // };
        // //创建标注工具对象
        // this.polygonTool = new T.PolygonTool(this.map, configPolygonTool);
        // this.polygonTool.addEventListener('draw', this.drawFinish)  // 监听双击绘制完成事件，调用drawFinish方法

        //拾取经纬度
        var cp = new T.CoordinatePickup(this.map, {callback: this.pickLngLat})
        cp.addEvent();

        //创建搜索对象
        var configSearch = {
          pageCapacity: 10,	//每页显示的数量
          onSearchComplete: this.localSearchResult	//接收数据的回调函数
        };
        this.localSearch = new T.LocalSearch(this.map, configSearch);
        // $("#keyWord").keyup(function () {
        //   this.localSearch.search(document.getElementById('keyWord').value, 4)
        // });


        //默认加载标注和多边形
        this.$nextTick(()=>{
          //创建标注对象
          this.markerPoint = new T.Marker(new T.LngLat(lng_lat.lng, lng_lat.lat));
          //向地图上添加标注
          this.map.addOverLay(this.markerPoint);

          var latlng = new T.LngLat(lng_lat.lng, lng_lat.lat);
          this.markerTitle = new T.Label({
            text: this.labelTitle,
            position: latlng,
            offset: new T.Point(-9, 0)
          });
          //创建地图文本对象
          this.map.addOverLay(this.markerTitle);

          console.log('this.pointList',this.pointList)

          if(this.shapeType == "polygon" && this.pointList != undefined && this.pointList.length > 0){
            var estatePoints = [];
            for (let index in this.pointList){
              let lng_lat = transformGCJ2WGS(this.pointList[index].lng, this.pointList[index].lat);
              console.log('lng_lat',lng_lat)
              console.log('new T.LngLat(lng_lat.lng, lng_lat.lat)', new T.LngLat(lng_lat.lng, lng_lat.lat))
              estatePoints.push(new T.LngLat(lng_lat.lng, lng_lat.lat));
            }
            console.log('this.estatePoints', this.estatePoints)

            //创建面对象
            this.polygon = new T.Polygon(estatePoints, {
              color: "blue", weight: 3, opacity: 0.5, fillColor: this.fillColor, fillOpacity: 0.5
            });
            //向地图上添加面
            this.map.addOverLay(this.polygon);
          } else if(this.shapeType == "polyline" && this.pointList != undefined && this.pointList.length > 0){
            var estatePoints = [];
            for (let index in this.pointList){
              let lng_lat = transformGCJ2WGS(this.pointList[index].lng, this.pointList[index].lat);
              console.log('lng_lat',lng_lat)
              console.log('new T.LngLat(lng_lat.lng, lng_lat.lat)', new T.LngLat(lng_lat.lng, lng_lat.lat))
              estatePoints.push(new T.LngLat(lng_lat.lng, lng_lat.lat));
            }
            console.log('this.estatePoints', this.estatePoints)

            //创建面对象
            this.polyline = new T.Polyline(estatePoints, {
              color: "blue", weight: 3, opacity: 0.5, fillColor: this.fillColor, fillOpacity: 0.5
            });
            //向地图上添加面
            this.map.addOverLay(this.polygon);
          } else if(this.shapeType == "circle" && this.radiusCircle != undefined && this.radiusCircle > 0){
            this.addCircle();
          }
        })
        console.log('地图初始化成功');
      } else {
        console.error('天地图API加载失败');
      }
    },
    addCircle(){
      //初始化地图对象
      // this.map = new T.Map("mapDiv");
      let lng_lat = transformGCJ2WGS(this.defaultLng, this.defaultLat);
      //设置显示地图的中心点和级别
      // this.map.centerAndZoom(new T.LngLat(lng_lat.lng, lng_lat.lat), this.zoom);
      // 定义该矩形的显示区域  圆的半径，以米点单位。
      var circle = new T.Circle(new T.LngLat(lng_lat.lng, lng_lat.lat), this.radiusCircle,{color:"blue",weight:5,opacity:0.8,fillColor:"#43dede",fillOpacity:0.8,lineStyle:"solid"});
      //向地图上添加圆
      this.map.addOverLay(circle);
    },
    handleClickAddress(address){
      console.log('handleClickAddress', address)
      let lng_lat = address.lonlat.split(',');
      this.map.centerAndZoom(new T.LngLat(lng_lat[0], lng_lat[1]), this.zoom); // 设置地图中心点和缩放级别
    },
    handleInput(){
      let value = document.getElementById('keyWord').value;
      console.log('this.searchValue', value);
      console.log('this.searchValue', this.localSearch);
      if(value!= undefined && value!= '' && this.localSearch){
        this.localSearch.search(value, 4)
      }else{
        this.clearAll();
        this.searchResultList = []
      }
    },
    localSearchResult(result) {
      //清空地图及搜索列表
      this.clearAll();

      //解析建议词信息
      this.suggests(result.getSuggests());
    },
    //解析建议词信息
    suggests(obj) {
      var that = this;
      if (obj) {
        console.log('suggests', obj);
        setTimeout(function (){
          that.$nextTick(()=> {
            that.searchResultList = obj;
            for (let index in obj) {
              let address = obj[index];
              if (address.lonlat != undefined && address.lonlat != '') {
                let lng_lat = address.lonlat.split(',');
                //创建标注对象
                var markerTem = new T.Marker(new T.LngLat(lng_lat[0], lng_lat[1]));
                //向地图上添加标注
                that.map.addOverLay(markerTem);
              }
            }
          });
        }, 300)
      }
    },
    //清空地图及搜索列表
    clearAll() {
      console.log('clearAll', this.searchMarker)
      this.map.clearOverLays();

      let that = this;
      setTimeout(function (){
        that.initMap();
      }, 800);
    },
    pickLngLat(lnglat) {
      // lnglat.lng.toFixed(6) + "," + lnglat.lat.toFixed(6);
      console.log('pickLngLat', lnglat)
      if(this.markerPoint!= null){
        this.map.removeOverLay(this.markerPoint)
      }
      if(this.markerTitle!= null){
        this.map.removeOverLay(this.markerTitle)
      }
      // let lng_lat = transformGCJ2WGS(this.defaultLng, this.defaultLat);
      //设置显示地图的中心点和级别
      // this.map.centerAndZoom(new T.LngLat(lnglat.lng.toFixed(6), lnglat.lat.toFixed(6)), this.zoom);
      this.markerPoint = new T.Marker(new T.LngLat(lnglat.lng.toFixed(6), lnglat.lat.toFixed(6)));
      this.map.addOverLay(this.markerPoint);

      var latlng = new T.LngLat(lnglat.lng.toFixed(6), lnglat.lat.toFixed(6));
      this.markerTitle = new T.Label({
        text: this.labelTitle,
        position: latlng,
        offset: new T.Point(-9, 0)
      });
      //创建地图文本对象
      this.map.addOverLay(this.markerTitle);

      this.$emit("pickLngLat", lnglat);
    },
    startPoly(){
      if(this.polygon != undefined){
        this.polygon.enableEdit();
      }else{
        console.log('新建多边形')
        if (this.polygonTool) this.polygonTool.close();
        var configPolygonTool = {
          showLabel: true,
          color: "blue", weight: 3, opacity: 0.5, fillColor: this.fillColor, fillOpacity: 0.5
        };
        //创建标注工具对象
        this.polygonTool = new T.PolygonTool(this.map, configPolygonTool);
        this.polygonTool.open();
        this.polygonTool.addEventListener('draw', this.drawHandle);
      }
    },
    drawHandle(e){
      console.log('drawHandle', e)
      // e.currentLnglats
      this.polygon = e.currentPolygon;
    },
    endPoly(){
      if(this.polygon != undefined){
        this.polygon.disableEdit();
        // console.log('this.polygon', this.polygon.getLngLats())

        console.log('this.polygon.getLngLats()', this.polygon.getLngLats()[0])
        let lastPoints = [];
        if(this.polygon.getLngLats().length > 0){
          for (let index in this.polygon.getLngLats()[0]){
            let point = this.polygon.getLngLats()[0][index];
            console.log('point', point)
            let lng_lat = transformGCJ02(point.lng, point.lat);
            let pointNew = {
              lng: lng_lat.lng,
              lat: lng_lat.lat,
            }
            lastPoints.push(pointNew);
          }
          this.$emit("finishEdit", lastPoints);
        }
      }
    },
    clearPoly(){
      this.polygon = null;
      this.map.clearOverLays();
      this.pickPointList = [];
    },
  }
}
</script>

<style scoped>
#map {
  width: 100%;
  height: 100%;
}
input, b, p {
  margin-left: 5px;
  font-size: 14px
}

/deep/ .tdt-control > div {
  display: none;
}

.search {
  font-size: 13px;
  border: 1px solid #999999;
  line-height: 27px;
  padding-left: 7px;
}

.suggests {
  background-color: white;
  margin: 10px -10px;
  font-size: 13px;
  border: 1px solid #999999;
  padding: 10px;
}


.ls {
  line-height: 27px;
  padding-left: 7px;
}

.prompt {
  background-color: white;
  display: none;
  font-size: 13px;
  border: 1px solid #999999;
}

.statistics {
  background-color: white;
  display: none;
  font-size: 13px;
  border: 1px solid #999999;
  overflow-y: scroll;
  height: 150px;
}


.lineData {
  background-color: white;
  display: none;
  font-size: 13px;
  border: 1px solid #999999;
}

.result {
  background-color: white;
  display: none;
  font-size: 12px;
  border: 1px solid #999999;
  line-height: 27px;
  padding-left: 7px;
}

</style>
